require(['grid', 'topBar', 'highcharts', 'date', 'zTreeCheckbox'], function () {
    var $top = $('#top'),
        $fileList = $("#fileList"),
        $mainList = $("#mainList"),
        isFirst = true,
        postData,
        editDialog,
        // loadMask,
        autoRefreshReq = null;

    //顶部栏初始化
    function topBarInit() {
        //顶部搜索栏
        $top.topBar({
            left: [
                {
                    type: 'filter',
                    search: function () {
                        search();
                    },
                    item: [
                        {
                            text: '时间段',
                            name1: 'beginTime',
                            name2: 'endTime',
                            format: 'yyyy-MM-dd HH:mm:ss',
                            type: 'dateLine'
                        }
                    ]
                }
            ],
            right: [
                {
                    text: '文件分析',
                    type: 'btn',
                    width: '698',
//                authority: '',
                    click: function () {
                        fileAnalysis();
                    }
                },

                {
                    text: '文件下载',
                    type: 'btn',
                    width: '698',
//                authority: '',
                    click: function () {
                        loadFile();
                    }
                }
            ]
        });
    }

    //grid初始化
    function gridInit() {
        function fileStFormat(value) {
            var val = '等待下载';
            switch (value) {
                case '1':
                    val = '下载中';
                    break;
                case '2':
                    val = '下载失败';
                    break;
                case '3':
                    val = '已下载';
                    break;
            }
            return val;
        }

        //暂时无用
        function genTimeFormat(value) {
            if (value) {
                return new Date(value).format('yyyy-MM-dd hh:mm:ss');
            } else {
                return "";
            }
        }

        $fileList.grid({
            url: "/loadFile/getLoadFileRcd.htm",
            height: "200",
            colModel: [
                {name: "rcrdId", index: "rcrdId", label: 'id', key: true, hidden: true},
                {name: "fileName", index: "fileName", label: '文件名', width: 150},
                {name: "fileSt", index: "fileSt", label: '文件状态', width: 80, formatter: fileStFormat},
                {name: "failInfo", index: "failInfo", label: '状态描述'},
                {name: "fileBeginTime", index: "fileBeginTime", label: '文件记录的开始时间', width: 110},
                {name: "fileEndTime", index: "fileEndTime", label: '文件记录的结束时间', width: 110}
            ],
            showPager: false,
            loadComplete: function (xhr) {
                if (isFirst) {
                    isFirst = false;
                } else {
                    if (xhr && xhr.msgType && xhr.msgType != "1" && xhr.msg) {
                        $.messager.alert("提示", xhr.msg, "info");
                    } else if (xhr && xhr.obj && $.isArray(xhr.obj) && xhr.obj.length > 0) {

                    } else {
                        $.messager.alert("提示", "当前时间区间没有图表分析的相关数据。", "info");
                    }
                }
            }
        });

        $mainList.grid({
            url: "/accidentPoint/searchAccidentPointPage.htm",
            height: "200",
            colModel: [
                {name: "rcrdId", index: "rcrdId", label: "id", key: true, hidden: true},
                {name: "licPltNo", index: "licPltNo", label: "车牌号"},
                {name: "drvName", index: "drvName", label: "驾驶员"},
                {name: "lineName", index: "lineName", label: "营运线路"},
                {name: "organName", index: "organName", label: "所属机构"},
                {name: "rcrdTime", index: "rcrdTime", label: "停车时间"},
                {
                    name: "operate", width: 130, label: '图表分析', title: false, align: 'center',
                    formatter: 'operArea',
                    formatoptions: [{
                        text: '图表分析',
                        css: 'operate-chart',
                        click: function (data) {
                            toShowDobChart(data.licPltNo, data.rcrdTime, data.drivName, data.lineName);
                        }
                    }]
                }
            ],
            multiselect: false,
            rownumbers: false,
            showPaper: true
        });
    }

    //封装请求参数
    //beginTime
    //endTime
    //carId/carIds
    //componentType
    function getPostData() {
        postData = $top.parent().getValues();
        postData.componentType = '04';

        if (!postData.beginTime || !postData.endTime) {
            $.messager.alert("警告", "请先选择开始和结束时间", "info");
            return false;
        }

        var nodes = commonFun.getLeftTreeSelectedNodes();
        if (nodes && nodes.length > 0) {
            postData.carId = nodes[0].id;
            postData.carIds = nodes[0].id;

            //console.log(postData);
            return true;
        } else {
            $.messager.alert("警告", "请先选择一辆车", "info");
            return false;
        }
    }

    var getfileList = function () {
        $fileList.grid('setGridParam', {
            datatype: "json",
            postData: postData
        }).trigger("reloadGrid");
    }

    //清除信息
    function clearGridData() {
        $fileList.grid('clearGridData');
        $mainList.grid('clearGridData');
    }

    function search() {
        if (getPostData()) {
            clearGridData();
            getfileList();
        }
    }

    //创建遮罩层
    // function createLoadMask() {
    //     loadMask = commonFun.createLoadMask($('body'));
    // }

    //清除遮罩层
    // function clearLoadMask() {
    //     if (loadMask) {
    //         loadMask.remove();
    //         loadMask = null;
    //     }
    // }

    // todo 自动刷新各个文件的状态
    function autoRefresh() {
        var fileNames = [];
        var rowIds = $fileList.getGridParam().selarrrow;

        $.each(rowIds, function (index, item) {
            var row = $fileList.getRowData(item);
            if (row.fileSt != '已下载') {
                fileNames.push(row.fileName);
            }
        });

        if (autoRefreshReq) {//如果之前的请求还在，取消之前的请求
            autoRefreshReq.abort();
        }
        
        autoRefreshReq = $.ajax({
            type: "POST",
            url: $.getProjectName() + "/loadFile/getLoadFileSt.htm",
            data: {
                fileNames: fileNames.join(','),
                beginTime: postData.beginTime,
                endTime: postData.endTime,
                carIds: postData.carIds,
                componentType: postData.componentType
            },
            dataType: "json",
            success: function (data) {
                autoRefreshReq = null;
                if (data && data.obj) {
                    var complete = true;
                    $.each(data.obj, function (index, item) {
                        $fileList.setRowData(item.rcrdId, item);
                        if (item.fileSt == '0' || item.fileSt == '1') {
                            setTimeout(autoRefresh, 4000);
                            complete = false;
                        }
                        if (complete) {
                            // clearLoadMask();
                        }
                    })
                } else {
                    // clearLoadMask();
                }
            }
        });

        /*autoRefreshReq = $.ajaxExt({
            url: "/loadFile/getLoadFileSt.htm",
            data: {
                fileNames: fileNames.join(','),
                beginTime: postData.beginTime,
                endTime: postData.endTime,
                carIds: postData.carIds,
                componentType: postData.componentType
            }
        }).done(function (data) {
            autoRefreshReq = null;
            if ($.isArray(data)) {
                var complete = true;
                $.each(data, function (index, item) {
                    $fileList.setRowData(item.rcrdId, item);
                    if (item.fileSt == '0' || item.fileSt == '1') {
                        setTimeout(autoRefresh, 4000);
                        complete = false;
                    }
                    if (complete) {
                        //clearLoadMask();
                    }
                })
            } else {
                //clearLoadMask();
            }
        });*/
    }

    // todo 文件下载
    function loadFile() {
        if (postData) {
            var fileNames = [];
            var rowIds = $fileList.getGridParam().selarrrow;

            $.each(rowIds, function (index, item) {
                var row = $fileList.getRowData(item);
                if (row.fileSt != '已下载') {
                    fileNames.push(row.fileName);
                    
                    $fileList.setRowData(row.rcrdId, {'fileSt': '1'});
                }
            });

            if (fileNames.length == 0) {
                $.messager.alert("提示", "请选择等待下载的文件", "info");
                return;
            }

            $.ajaxExt({
                url: "/loadFile/getLoadFiles.htm",
                data: {
                    carIds: postData.carIds,
                    fileNames: fileNames.join(','),
                    ftpUrl: "ftp_accident_path",
                    componentType: postData.componentType
                }
            }).done(function () {
                // createLoadMask();
                autoRefresh();
            });
        } else {
            $.messager.alert("警告", "请先进行查询", "info");
        }
    }

    //文件分析
    function fileAnalysis() {
        var rowIds = $fileList.getGridParam().selarrrow;
        var fileRdIds = [];
        $.each(rowIds, function (index, item) {
            var row = $fileList.getRowData(item);
            if (row.fileSt == '已下载') {
                fileRdIds.push(row.rcrdId);
            }
        });
        if (fileRdIds.length == 0) {
            $.messager.alert("提示", "请选择已下载的文件进行分析。", "info");
            return;
        }

        //对文件进行分析
        $mainList.grid('setGridParam', {
            page: 1,
            datatype: 'json',
            postData: {
                fileRdIds: fileRdIds.toString()
            }
        }).trigger("reloadGrid");
    }

    /**
     * 获取表单对话框，如果没有就先创建
     * @param option {object} 对话框配置
     * @returns {jQuery}
     */
    function getEditDialog(option) {
        option = option || {};
        if (editDialog) {
            editDialog.dialog('open');
            if (option.title) {
                editDialog.dialog('setOption', 'title', option.title);
            }
        } else {
            editDialog = $('<div>').dialog({
                title: option.title || '图表分析',
                url: './safety/report/commDobChartDialog.htm',
                height: $(window.parent).height(),
                width: $(window.parent).width(),
                autoOpen: true,
                buttons: []
            });
        }
        return editDialog;
    }

    var toShowDobChart = function (licPltNo, rcrdTime, drivName, lineName) {
        var categories = [];

        var initCategories = function () {
            // 设置为空值
            categories = [];

            var scale = 0;
            for (var i = 0; i < 101; i++) {
                categories.push(scale.toFixed(1));
                scale += 0.2;
            }
            categories.push(scale.toFixed(1));
        }

        $.ajaxExt({
            url: "/accidentPoint/getAccidentPointChart.htm",
            data: {licPltNo: licPltNo, rcrdTime: rcrdTime}
        }).done(function (responseData) {
            if (!responseData || Object.prototype.toString.call(responseData) !== "[object Array]") {
                $.messager.alert("提示", "没有进行图表分析的数据。", "info");
                return;
            }

            //console.log(responseData);

            var data = {
                info: {},
                categories: [],
                sudu: [],
                zhuansu: [],
                qianqiya: [],
                houqiya: [],
                shuiwen: [],
                youya: [],
                zongdianya: [],
                zongdianliu: [],
                dianjizhuansu: [],
                soc: [],
                d10: [],
                d9: [],
                d8: [],
                d7: [],
                d6: [],
                d5: [],
                d4: [],
                d3: [],
                d2: [],
                d1: []
            };

            //console.log(categories);

            //动态生成x轴数据
            initCategories();
            data.categories = categories;

            //介绍信息
            data.info.type = '1';
            data.info.licPltNo = licPltNo;
            data.info.drvName = (drivName === 'null' ? '-' : drivName);
            data.info.lineName = lineName;
            data.info.occuTime = rcrdTime;
            
            var item = {},starttag = 0;
            for (var i = 0; i < 102; i++) {
                if (i < responseData.length) {
                    item = responseData[i];
                    
                    //标注发生点
                    if(starttag == 0){
                        if(rcrdTime == item.rcrdTime.substr(0,19)){
                            data.info.starttag = i;
                            starttag = 1;
                        }
                    }

                    data.d10.push(item.igniSwtc !== '1' ? 200 : null);
                    data.d9.push(item.swtcSt[0] === '1' ? 190 : null);
                    data.d8.push(item.swtcSt[1] === '1' ? 180 : null);
                    data.d7.push(item.swtcSt[2] === '1' ? 170 : null);
                    data.d6.push(item.swtcSt[3] === '1' ? 160 : null);
                    data.d5.push(item.swtcSt[4] === '1' ? 150 : null);
                    data.d4.push(item.swtcSt[5] === '1' ? 140 : null);
                    data.d3.push(item.swtcSt[6] === '1' ? 130 : null);
                    data.d2.push(item.swtcSt[7] === '1' ? 120 : null);
                    data.d1.push(item.swtcSt[8] === '1' ? 110 : null);

                    data.sudu.push(item.spdOfMotVhi);
                    data.zhuansu.push(item.rtteSpd);
                    data.qianqiya.push(item.preAirPrs);
                    data.houqiya.push(item.lastAirPrs);
                    data.shuiwen.push(item.wteTept);
                    data.youya.push(item.engnOilPrs);
                    data.zongdianya.push(item.totalVtg);
                    data.zongdianliu.push(item.totalEltCrt);
                    data.dianjizhuansu.push(item.eltMhyRtteSpd);
                    data.soc.push(item.soc);
                } else {
                    data.d10.push(null);
                    data.d9.push(null);
                    data.d8.push(null);
                    data.d7.push(null);
                    data.d6.push(null);
                    data.d5.push(null);
                    data.d4.push(null);
                    data.d3.push(null);
                    data.d2.push(null);
                    data.d1.push(null);
                }
            }

            var option = {};
            option.title = '事故疑点图表分析';
            getEditDialog(option).dialog('exec', 'showDobChart', [data]);
        });
    }

    topBarInit();
    gridInit();
});